// 正式
// let baseUrl = 'https://dev-api.lefujin.cn/api/'
// 测试
let baseUrl = 'https://api.lefujin.cn/api/'
var timestamp = Date.parse(new Date()) / 1000
import md5 from 'js-md5'
let Base64 = require('js-base64').Base64

// 封装的uni.request请求
function $get(url, data = {}, header = "application/json") {
	const token = uni.getStorageSync('token')
	return new Promise(function(resolve, reject) {
		uni.request({
			url: baseUrl + url,
			method: 'GET',
			data: data,
			dataType: 'json',
			header: {
				Token: token == null ? '' : token,
				'Content-Type': header,
				'sign': createSign(),
				"terminal":9
			},
			// header:header,
			success: function(res) {
				if (res.statusCode == 200) {
					if (res.data.code == 0) {
						resolve(res.data)
					} else if(res.data.code == 8100 || res.data.code == 8000 || res.data.code == 4100) {
						uni.showToast({
							title:res.data.msg,
							icon:"none"
						})
						uni.removeStorage({
							key: 'token',
							success: function(res) {
							}
						});
					}else {
						uni.showToast({
							title:res.data.msg,
							icon:"none"
						})
					}
				}else {
					console.log(res);
				}
			},
			fail: function(e) {
				console.log(e)
				reject(e)
			}
		})
	})
}

function createSign() {
	let last_num = timestamp.toString().slice(-1)
	if (last_num <= 3) {
		last_num = 3;
	}else if(last_num > 3 && last_num <= 6) {
		last_num = 6;
	}else if(last_num > 6 && last_num <= 9) {
		last_num = 9;
	} else {
		last_num = 0;
	}
	let new_str = timestamp.toString().slice(0,9) + last_num
	
	let md5_str = md5(new_str);
	let str_split = md5_str.split('')
	let new_str_split = str_split.sort()
	return Base64.encode(new_str_split.join(""));
}

function $post(url, data = {}, header = "application/json") {
	// console.log(uni.getStorageSync('token'),"<===============")
	const token = uni.getStorageSync('token')
	return new Promise(function(resolve, reject) {
		uni.request({
			url: baseUrl + url,
			method: 'POST',
			data: data,
			dataType: 'json',
			header: {
				Token: token == null ? '' : token,
				'Content-Type': header,
				'sign': createSign(),
				"terminal":9
			},
			// header:header,
			success: function(res) {
				if (res.statusCode == 200) {
					if (res.data.code == 0) {
						resolve(res.data)
					} else if(res.data.code == 8100 || res.data.code == 8000 || res.data.code == 4100) {
						uni.showToast({
							title:res.data.msg,
							icon:"none"
						})
						uni.removeStorage({
							key: 'token',
							success: function(res) {
							}
						});
					}else {
						uni.showToast({
							title:res.data.msg,
							icon:"none"
						})
					}
				}else {
					console.log(res);
				}
				
			},
			fail: function(e) {
				// console.log()
				reject(e)
			}
		})
	})
}

// 封装的请求方法需要暴露出去
module.exports = {
	$get,
	$post,
}